/**
 * 获取消息推送平台
 * @returns
 */
export const getPushPlatform = () => {
	let platform = '';
	//#ifdef APP-PLUS || APP-PLUS-NVUE
	platform = uni.getSystemInfoSync().platform;
	// #endif
	// #ifdef H5
	platform = 'web';
	// #endif
	// #ifdef MP-WEIXIN
	platform = 'miniapp';
	// #endif

	return platform;
};

/**
 * 判断运行平台
 * @returns
 */
export const getPlatform = () => {
	let platform = 'APP';
	// #ifdef H5
	platform = 'H5';
	// #endif
	// #ifdef MP-WEIXIN
	platform = 'MP-WEIXIN';
	// #endif
	return platform;
};

/**
 * 判断app是android还是ios
 * @returns
 */
export const geAppPlatform = () => {
	//#ifdef APP-PLUS || APP-PLUS-NVUE
	return uni.getSystemInfoSync().platform;
	// #endif
};

// 复制到剪切板
export const copyClipboard = (data, title = '内容已复制') => {
	uni.setClipboardData({
		data,
		success: (res) => {
			uni.showToast({
				duration: 5000,
				title,
				icon: 'none'
			})
		}
	});
};

// 拨打电话
export const phoneCall = (phoneNumber) => {
	uni.makePhoneCall({
		phoneNumber
	});
};
// 退出APP
export const appQuit = () => {
	// #ifdef APP-PLUS
	if (plus.os.name.toLowerCase() === 'android') {
		plus.runtime.quit();
	} else {
		const threadClass = plus.ios.importClass('NSThread');
		const mainThread = plus.ios.invoke(threadClass, 'mainThread');
		plus.ios.invoke(mainThread, 'exit');
		// ios11
		plus.ios.import('UIApplication').sharedApplication().performSelector('exit');
	}
	// #endif
};

// 从本地相册选择图片或使用相机拍照
export const chooseImage = ({
	count = 1,
	sizeType = ['original', 'compressed'],
	extension,
	sourceType = ['album', 'camera'],
	crop
}) => {
	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count,
			sizeType,
			extension,
			sourceType,
			crop,
			success: ({
				tempFilePaths
			}) => resolve(tempFilePaths),
			fail: (err) => reject(err)
		});
	});
};

// 深拷贝
export function deepCopy(data) {
	//string,number,bool,null,undefined,symbol
	//object,array,date
	if (data && typeof data === 'object') {
		//针对函数的拷贝
		if (typeof data === 'function') {
			let tempFunc = data.bind(null);
			tempFunc.prototype = deepCopy(data.prototype);
			return tempFunc;
		}

		switch (Object.prototype.toString.call(data)) {
			case '[object String]':
				return data.toString();
			case '[object Number]':
				return Number(data.toString());
			case '[object Boolean]':
				return new Boolean(data.toString());
			case '[object Date]':
				return new Date(data.getTime());
			case '[object Array]':
				var arr = [];
				for (let i = 0; i < data.length; i++) {
					arr[i] = deepCopy(data[i]);
				}
				return arr;

				//js自带对象或用户自定义类实例
			case '[object Object]':
				var obj = {};
				for (let key in data) {
					//会遍历原型链上的属性方法，可以用hasOwnProperty来控制 （obj.hasOwnProperty(prop)
					obj[key] = deepCopy(data[key]);
				}
				return obj;
		}
	} else {
		//string,number,bool,null,undefined,symbol
		return data;
	}
}
/**
 * json转译
 * @returns
 */
export const toJson = (value) => {
	let result;
	try {
		result = JSON.parse(value);
	} catch (e) {
		result = value;
	}
	return result;
};

/**
 * 去一对一聊天页面
 * @param toImUserId 对方的im的userId
 */
export function toDialoguePage(toImUserId) {
	let url = `/tim/pages/dialogue/index?toImUserId=${toImUserId}`;
	uni.navigateTo({
		url
	});
}

/**
 * 去找客服页面
 */
export function clickBtn(id) {
	uni.navigateTo({
		url: `/transport/pages/service/index?id=${id}`
	})

}

/**
 * 获取当前路由
 */
export const getCurRoute = () => {
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let curRoute = routes[Math.max(routes.length - 1, 0)].route; //获取当前页面路由
	return curRoute;
};

// 打开外部链接
export const handleOpenLinks = (url) => {
	// #ifdef H5
	window.open(url);
	// #endif
	// #ifdef APP-PLUS || APP-PLUS-NVUE || APP-NVUE
	let wv = null; //计划创建的webview
	if (!wv) {
		wv = plus.webview.create('', 'custom-webview', {
			plusrequire: 'none', //禁止远程网页使用plus的API，有些使用mui制作的网页可能会监听plus.key，造成关闭页面混乱，可以通过这种方式禁止
			'uni-app': 'none', //不加载uni-app渲染层框架，避免样式冲突
			top: uni.getSystemInfoSync()
				.statusBarHeight, //放置在titleNView下方。如果还想在webview上方加个地址栏的什么的，可以继续降低TOP值
			bottom: '0',
			popGesture: 'none', // 窗口的侧滑返回功能
			subNViews: [{
				id: 'web-go-back',
				styles: {
					top: '10px',
					left: '10px',
					width: '30px',
					height: '30px'
				},
				tags: [{
					tag: 'img',
					src: 'https://img.sanytruck.com/b72ed727efe14c4267e6a196bc92dde7',
					position: {
						width: '30px',
						height: '30px'
					}
				}]
			}]
		});
		plus.nativeObj.View.getViewById('web-go-back').addEventListener('touchstart', (e) => wv.close(), false);
	}
	wv.loadURL(url);
	let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
	let curRoute = routes[Math.max(routes.length - 1, 0)]; //获取当前页面路由
	const currentWebview = curRoute
		.$getAppWebview(); //此对象相当于html5plus里的plus.webview.currentWebview()。在uni-app里vue页面直接使用plus.webview.currentWebview()无效
	currentWebview.append(wv); //一定要append到当前的页面里！！！才能跟随当前页面一起做动画，一起关闭
	// #endif
};

// 分割字符串
export const replaceStr = (str = '', start = 0, end = 0, char = '') => {
	const newStr = str.substring(0, start) + char + str.substring(end);
	return newStr.replace(/(.{4})/g, '$1 ');
};
export const cardNoStr = (str) => {
	return String(str).substr(0, 4) + '********' + String(str).substr(-4);
};
/**
 * 手机号隐藏中间四位**
 * @returns
 */
export function getHideTel(tel) {
	const reg = /^(\d{3})\d{4}(\d{4})$/;
	return (tel + '').replace(reg, '$1****$2');
}

/**
 * 隐藏身份证中间**
 * @returns
 */
export function hideIdCard(value) {
	if (!value) return '';
	let str1 = value.slice(0, 6);
	let str2 = '';
	let str3 = value.slice(14);
	if (value.length === 15) {
		str2 = '******';
	} else {
		str2 = '********';
	}
	return str1 + str2 + str3;
}

/**
 * 获取微信分享的实例
 */
export const getWeixinShareInstance = () => {
	return new Promise((resolve, reject) => {
		//获取当前显示的webview
		const pages = getCurrentPages();
		const page = pages[pages.length - 1];
		const currentWebview = page.$getAppWebview();
		//调用H5+APP的扩展API
		let shares = {};
		const pusher = plus.share.getServices((s) => {
			for (var i in s) {
				var t = s[i];
				shares[t.id] = t;
			}
			resolve(shares['weixin']);
		}, (e) => {
			reject(null);
		});
		//放入当前的webview
		currentWebview.append(pusher);
	});
};

/**
 * 延时执行
 * @param millisecond 延时的毫秒数
 * @return {Promise<undefined>}
 */
export function delay(millisecond = 0) {
	return new Promise(resolve => {
		setTimeout(function() {
			resolve(undefined)
		}, millisecond)
	})
}

export function getUrlCode(name) {
	return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [,
		''
	])[1].replace(/\+/g, '%20')) || null
}


/**
 * 简单深拷贝的方法
 */
export function setDeepCopy(val) {
	return JSON.parse(JSON.stringify(val))
}

/**
 * base64转file
 */
export function base64ToFile(base64, fileName) {
  let arr = base64.split(",");
  let mime = arr[0].match(/:(.\*?);/)[1];
  let bstr = atob(arr[1]);
  let n = bstr.length;
  let u8arr = new Uint8Array(n);

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], fileName, { type: mime });
}







export default {
	getPlatform,
	geAppPlatform,
	copyClipboard,
	phoneCall,
	appQuit,
	chooseImage,
	deepCopy,
	toJson,
	getCurRoute,
	handleOpenLinks,
	replaceStr,
	cardNoStr,
	getHideTel,
	hideIdCard,
	getWeixinShareInstance,
	getUrlCode,
	setDeepCopy, // 简单深拷贝
	
	base64ToFile, // base转file
}